#include "chatserver.hpp"
#include <functional>
#include "ChatService.hpp"
#include <string>
#include "usermodel.hpp"
using namespace std;
using namespace muduo;
using namespace muduo::net;

ChartServer::ChartServer(muduo::net::EventLoop* loop,
                         const muduo::net::InetAddress& listenAddr) : loop(loop),
                                                                      server(loop, listenAddr, "ChatServer") {
    using namespace placeholders;
    server.setConnectionCallback(std::bind(&ChartServer::OnConnectedCb, this, _1));
    server.setMessageCallback(std::bind(&ChartServer::OnMessageCb, this, _1, _2, _3));
    server.setThreadNum(4);
}
ChartServer::~ChartServer() {
}
void ChartServer::Start() {
    server.start();
}
void ChartServer::OnMessageCb(const muduo::net::TcpConnectionPtr& conn,
                              muduo::net::Buffer* buff,
                              muduo::Timestamp time) {
    // 接收到所有的消息，然后回显
    std::string msg(buff->retrieveAllAsString());
    json js = json::parse(msg);
    auto handler = ChatService::Instance()->GetHandler(js["msgId"]);
    handler(conn, js, time);
    UserModel model;
}
void ChartServer::OnConnectedCb(const muduo::net::TcpConnectionPtr& conn) {
    LOG_INFO << "EchoServer - " << conn->peerAddress().toIpPort() << " -> "
           << conn->localAddress().toIpPort() << " is "
           << (conn->connected() ? "UP" : "DOWN");
    if (!conn->connected()) {
        LOG_INFO << "EchoServer - " << conn->peerAddress().toIpPort() << " is DOWN";
        ChatService::Instance()->ClinetCloseException(conn);
        conn->shutdown();
    }
}
// {"msgId": 1, "name": "nullptr", "password": "123456"}